<?php

namespace App\Repositories\Admin;

use App\BaseRepository;
use App\Model\SysRegion;
use Illuminate\Validation\Rule;

class SysRegionRepository extends BaseRepository
{
    //模型名称
    protected $modelName = "App\Model\SysRegion";

//    protected $allowApiMethod = ['index','show',''];

    protected $appendCreatorAndUpdater = true;

    protected $appendUserId = true;

    protected function relationLoad()
    {
        return ['subdivision','subdivision.country'];
    }

    protected function getShowRespondData($model)
    {
        return $model->load('subdivision','subdivision.country');
    }

    public function export()
    {
        $data = $this->query()->orderBy('id','asc')->select(['id','region','chRegion','regionCode','subdivision_id'])
            ->get()->toArray();
        return $this->exportFile('产区码模板',$data);
    }

    protected function commonRules()
    {
        return [
            'subdivision_id' => 'required',
        ];
    }

    protected function storeRules()
    {
        return [
            'region' => [
                'required',
                Rule::unique('sys_region')->whereNull('deleted_at')
            ],
            'chRegion' => [
                'required',
                Rule::unique('sys_region')->whereNull('deleted_at')
            ],
            'regionCode' => [
                'required',
                Rule::unique('sys_region')->whereNull('deleted_at')
            ]
        ];
    }
    protected function updateRules($id)
    {
        return [
            'region' => [
                'required',
                Rule::unique('sys_region')->ignore($id)->whereNull('deleted_at')
            ],
            'chRegion' => [
                'required',
                Rule::unique('sys_region')->ignore($id)->whereNull('deleted_at')
            ],
            'regionCode' => [
                'required',
                Rule::unique('sys_region')->ignore($id)->whereNull('deleted_at')
            ]
        ];
    }

    protected function processRelationFilter($query,$key, $operator, $value)
    {
        if ($key == "country_id" && $operator){
            return $query->whereRaw('`subdivision_id` in (select id from `sys_subdivision` where country_id '.$operator .$value.')');
        }
        return $query;
    }
}